import { store } from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Info } from '@/store/modules/account/info';
import { Router } from 'vue-router';
import { asyncRoutes, constantRoutes, router } from '@/router/index';
import { whiteList } from '@/router/whiteList';

export const getTitle = (title: string): string => {
  if (title) {
    return `${title} | ${store.getters['settings/title']}`;
  } else {
    return store.getters['settings/title'];
  }
};

export const decorateRouter = (router: Router): Router => {
  NProgress.configure({ showSpinner: false });

  router.onError(err => {
    console.log(err.message);
  });

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const {
      path,
      meta: { title },
    } = to;
    // console.log(from, to);
    document.title = getTitle(title);
    if (await store.dispatch('account/localValidate', () => {})) {
      // console.log('has token');
      if (path === '/login') {
        // console.log('to /');
        next({ path: '/' });
      } else {
        const info: Info = store.getters['account/info'];
        const routeTime: string = store.getters['routes/time'];
        // console.log('compare time', info.time, routeTime);
        if (info.time === routeTime) {
          // console.log('time is same', info.time);
          next();
        } else {
          try {
            // console.log('dispatch routes/filterAsyncRoutes');
            await store.dispatch('routes/filterAsyncRoutes', info);

            // 解决刷新后路由定位到 AsyncRoutes 的问题
            if (to.redirectedFrom) {
              // console.log('next to.redirectedFrom');
              next({
                path: to.redirectedFrom.path,
                query: to.redirectedFrom.query,
                replace: true,
              });
            } else {
              // console.log('next replace:true');
              next({
                path: to.path,
                query: to.query,
                replace: true,
              });
            }
          } catch (e) {
            // console.log(e);
            await store.dispatch('account/logout');
            // console.log('next login?redirect');
            next(`/login?redirect=${path}`);
          }
        }
      }
    } else {
      // console.log('no token, check whiteList');
      // let result = false;
      // for (const v of whiteList) {
      //   if (path.includes(v)) {
      //     result = true;
      //   }
      // }
      if (whiteList.includes(path)) {
        // in the whitelist, go directly
        // console.log('next whitelist');
        next();
      } else {
        // console.log('next whitelist redirect');
        // other pages that do not have role to access are redirected to the login page.
        next(`/login?redirect=${path}`);
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });

  return router;
};

export const resetRouter = (): void => {
  asyncRoutes.forEach(route => {
    const constantRoute = constantRoutes.find(route => route.name === route.name);
    if (constantRoute) {
      router.addRoute(constantRoute);
    } else {
      router.removeRoute(route.name);
    }
  });
};
